<%@ page language="java" contentType="text/html; charset=US-ASCII"
	pageEncoding="US-ASCII"%>
<%@ page import="java.sql.*"%>
<%@ page import="java.util.*"%>
<%@ page import="ca.radiologydb.util.Template"%>
<%@ page import="ca.radiologydb.util.ConnectionManager" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Search</title>
<%
	// @author Nicholas Liu
	// The Search page. Visible to all, but cannnot actually use without permissions set by login.

	Template template = new Template(this.getServletContext()
			.getRealPath("/").toString());
	out.println(template.getTemplateTop());
%>
</head>
<body>
	<form method="post" action="search.jsp">
		Select search timeframe: <select name="time">
			<option value="All">ALL</option>
			<option value="Before">Before</option>
			<option value="After">After</option>
			<option value="On">On</option>
			<option value="Between">Between</option>
		</select><br> Only valid if selection is not "ALL"<br> Timeframe 1
		(mm-dd-yyyy): <input type=text name=timeone><br> Only
		valid if selection is "between:"<br> Timeframe 2 (mm-dd-yyyy): <input
			type=text name=timetwo><br> Select prescribed date or
		test date: (Only used if timeframe is not ALL)<br> <select
			name="datetype">
			<option value="prescribing_date">Prescribed Date</option>
			<option value="test_date">Test Date</option>
		</select><br> Search terms (use commas to separate values):<br>
		Keywords:<input type=text name=ttype><br> Sort by:<br>
		<select name="sort">
			<option value="Default">Default</option>
			<option value="MRecent">Most Recent</option>
			<option value="LRecent">Least Recent</option>
		</select> <input type=submit name=bSubmit value=Submit>

	</form>
	<%
		// Okay, so our search will work as such: if the 3 fields specified contain any of the keywords, 
		// then that row will be shown, ranked based on the algorithm given.
		if (session.getAttribute("username") == null || session.getAttribute("usertype") == null) {
			out.println("Cannot display results as you're not logged in.");
			out.println("<a href='login.jsp'>Login</a>");
		} else if (request.getParameter("bSubmit") != null) {
			ConnectionManager manager = new ConnectionManager();
			Connection conn = manager.getConnection();

			Statement stmt = null;
			ResultSet rset = null;
			boolean add = false;

			String sql;

			// create sql query.
			sql = "SELECT DISTINCT radiology_record.patient_name, radiology_record.doctor_name, radiologist_name, test_type, ";
			sql += "prescribing_date, test_date, diagnosis, description, ";
			sql += "(score(0)*6 + score(1)*3 + score(2)) as rank, radiology_record.record_id as id from radiology_record, family_doctor where";

			// deal with case of time being selected.
			if (request.getParameter("time").equals("Before")) {
				//out.println(request.getParameter("datetype"));
				sql += " " + request.getParameter("datetype")
						+ " < to_date('" + request.getParameter("timeone")
						+ "','mm-dd-yyyy')";
				add = true;
			} else if (request.getParameter("time").equals("After")) {
				sql += " " + request.getParameter("datetype")
						+ " > to_date('" + request.getParameter("timeone")
						+ "','mm-dd-yyyy')";
				add = true;
			} else if (request.getParameter("time").equals("On")) {
				sql += " " + request.getParameter("datetype")
						+ " = to_date('" + request.getParameter("timeone")
						+ "','mm-dd-yyyy')";
				add = true;
			} else if (request.getParameter("time").equals("Between")) {
				sql += " (" + request.getParameter("datetype")
						+ " > to_date('" + request.getParameter("timeone")
						+ "','mm-dd-yyyy') AND ";
				sql += request.getParameter("datetype") + " < to_date('"
						+ request.getParameter("timetwo")
						+ "','mm-dd-yyyy'))";
				add = true;
			}

			// deal with case of keywords inputted.
			// we match the case that it may be found inside... using %'s
			String ttype;
			String tcontains = "";
			if (!request.getParameter("ttype").trim().isEmpty()) {
				ttype = request.getParameter("ttype");
				StringTokenizer st = new StringTokenizer(ttype, ",", false);
				while (st.hasMoreTokens()) {
					String token = st.nextToken();
					// turn each search term into a fuzzy term using oracle-text operators.
					tcontains += "| %" + token.trim() + "% ";
				}
				// need to remove the first "| "
				tcontains = tcontains.substring(2);
				tcontains = tcontains.trim();
				//out.println(tcontains);
			}
			if (tcontains.isEmpty()) {
				// search for anything if empty.
				tcontains = "%";
			}

			// get the username/usertype
			String username = (String) session.getAttribute("username");
			String usertype = (String) session.getAttribute("usertype");

			// if there was a time period selected, need to append this.
			if (add) {
				sql += " AND";
			}

			// score variable stuff and search for keywords.
			sql += " (contains(radiology_record.patient_name,'" + tcontains
					+ "',0)>0";
			sql += " OR contains(diagnosis,'" + tcontains + "',1)>0 ";
			sql += " OR contains(description,'" + tcontains + "',2)>0)";
			add = true;

			// User Security Module.
			if (usertype.equals("d")) {
				if (add) {
					sql += " AND";
					add = false;
				}
				// if the patient has current doctor as a doctor, match either current doctor or
				// or any other records where this patient had imaging taken
				sql += " ((radiology_record.doctor_name = '"
						+ username
						+ "') OR (radiology_record.patient_name = family_doctor.patient_name AND"
						+ " family_doctor.doctor_name = '" + username
						+ "'))";
			} else if (usertype.equals("r")) {
				if (add) {
					sql += " AND";
					add = false;
				}
				// Only radiologist.
				sql += " (radiology_record.radiologist_name = '" + username
						+ "')";
			} else if (usertype.equals("p")) {
				if (add) {
					sql += " AND";
					add = false;
				}
				// Only current patient.
				sql += " (radiology_record.patient_name = '" + username
						+ "')";
			}
			
			// Sorting parameters - date asc/desc or default ranking.
			if (request.getParameter("sort").equals("MRecent")) {
				sql += " ORDER BY " + request.getParameter("datetype")
						+ " DESC";
			} else if (request.getParameter("sort").equals("LRecent")) {
				sql += " ORDER BY " + request.getParameter("datetype")
						+ " ASC";
			} else {
				sql += " ORDER BY rank DESC";
			}

			//out.println(sql);

			try {
				stmt = conn.createStatement();
				rset = stmt.executeQuery(sql);
			} catch (Exception ex) {
				out.println("<hr>" + ex.getMessage() + "<hr>");
			}

			// print out result table header
			out.println("<table border=1>");
			out.println("<tr>");
			out.println("<th>Patient Username</th>");
			out.println("<th>Doctor Username</th>");
			out.println("<th>Radiologist Username</th>");
			out.println("<th>Test Type</th>");
			out.println("<th>Prescription Date</th>");
			out.println("<th>Test Date</th>");
			out.println("<th>Diagnosis</th>");
			out.println("<th>Description</th>");
			out.println("<th>Thumbnail</th>");
			out.println("</tr>");

			// print out all results.
			while (rset != null && rset.next()) {
				out.println("<tr>");
				out.println("<td>");
				out.println(rset.getString(1));
				out.println("</td>");
				out.println("<td>");
				out.println(rset.getString(2));
				out.println("</td>");
				out.println("<td>");
				out.println(rset.getString(3));
				out.println("</td>");
				out.println("<td>");
				out.println(rset.getString(4));
				out.println("</td>");
				out.println("<td>");
				out.println(rset.getDate(5));
				out.println("</td>");
				out.println("<td>");
				out.println(rset.getDate(6));
				out.println("</td>");
				out.println("<td>");
				out.println(rset.getString(7));
				out.println("</td>");
				out.println("<td>");
				out.println(rset.getString(8));
				out.println("</td>");
				
				// use recid to get correct images.
				int recid = rset.getInt(10);

				sql = "SELECT image_id from pacs_images where record_id = "
						+ recid;
				Statement stmt2 = conn.createStatement();
				ResultSet rset2 = stmt2.executeQuery(sql);
				int imgid = 0;
				if (rset2 != null && rset2.next()) {
					imgid = rset2.getInt(1);
				}
				
				out.println("<td>");
				// clicking on the image will open the full size one in a new tab.
				// print out thumbnail too.
				out.println("<a href=\"GetBigPic?type=full_size&imgid="
						+ imgid + "\" target=\"_blank\"><img src=\"GetBigPic?type=thumbnail&imgid="
						+ imgid + "\"></a>");
				
				out.println("</td>");
				out.println("</tr>");

			}
			out.println("</table>");

			conn.close();
			manager.closeConnection();
		}
	%>
</body>
</html>